package com.zpkj.portal.interceptor;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.zpkj.portal.dto.ResponseParameter;
import com.zpkj.portal.utils.Constant;

import nl.bitwalker.useragentutils.OperatingSystem;
import nl.bitwalker.useragentutils.UserAgent;

@Aspect
@Component
public class InterfaceLogAspect {
	// 本地异常日志记录对象
//	private static final Logger logger = LoggerFactory.getLogger(InterfaceLogAspect.class);

	// 定义Controller层切点
	@Pointcut("execution(* com.zpkj.portal.web.*Controller.*(..))")
	public void controllerAspect() {
	}

	// /**
	// * 前置通知 用于拦截Controller层记录用户的操作(暂时不用）
	// *
	// * @author v1pin-rnn
	// * @param joinPoint 切点
	// */
	// @Before("controllerAspect()")
	// public void doBefore(JoinPoint joinPoint) {
	// }

	/**
	 * 前置通知 用于拦截Controller层记录用户的操作
	 * @param joinPoint 切点
	 * @param rtv 返回参数
	 */
	@AfterReturning(pointcut = "controllerAspect()", argNames = "rtv", returning = "rtv")
	public void doAfter(JoinPoint joinPoint, Object rtv) throws Throwable {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		try {
//			String ip = request.getRemoteAddr();
			String agent = request.getHeader("User-Agent");
			String osName = "";
			if (StringUtils.isNotEmpty(agent)) {
				UserAgent userAgent = UserAgent.parseUserAgentString(agent);
				OperatingSystem os = userAgent.getOperatingSystem();
				osName = os.getName();
				if (StringUtils.isEmpty(osName)
						|| osName.toLowerCase().equals("unknown")) {
					agent = agent.toLowerCase();
					if (agent.indexOf("ios") >= 0
							|| agent.indexOf("iphone") >= 0
							|| agent.indexOf("mac") >= 0
							|| agent.indexOf("ipad") >= 0
							|| agent.indexOf("ipod") >= 0) {
						osName = "IOS";
					} else if (agent.indexOf("android") >= 0) {
						osName = "Android";
					}
				}
			}
//			String returnParam = "";
//			if (rtv != null) {
//				returnParam = new Gson().toJson(rtv);
//			}
//			String methodName = joinPoint.getTarget().getClass().getSimpleName() + "." + joinPoint.getSignature().getName();
//			logger.info("返回参数:【{}】 IP:{} 终端:{} 出参:{}", methodName, ip, osName,returnParam);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 异常通知 用于拦截service层记录异常日志
	 * 
	 * @author v1pin-rnn
	 * @param joinPoint
	 * @param e
	 * @throws Exception 
	 */
	@AfterThrowing(pointcut = "controllerAspect()", throwing = "e")
	public void doAfterThrowing(JoinPoint joinPoint, Throwable e) throws Exception {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
//		String ip = request.getRemoteAddr();
		String agent = request.getHeader("User-Agent");
		String osName = "";
		if (StringUtils.isNotEmpty(agent)) {
			UserAgent userAgent = UserAgent.parseUserAgentString(agent);
			OperatingSystem os = userAgent.getOperatingSystem();
			osName = os.getName();
			if (StringUtils.isEmpty(osName)
					|| osName.toLowerCase().equals("unknown")) {
				agent = agent.toLowerCase();
				if (agent.indexOf("ios") >= 0 || agent.indexOf("iphone") >= 0
						|| agent.indexOf("mac") >= 0
						|| agent.indexOf("ipad") >= 0
						|| agent.indexOf("ipod") >= 0) {
					osName = "IOS";
				} else if (agent.indexOf("android") >= 0) {
					osName = "Android";
				}
			}
		}
		ResponseParameter result = new ResponseParameter();
		String errorCode = StringUtils.isEmpty(e.getMessage()) ? Constant.ReturnCode.CODE_0000 : e.getMessage();
		String message = Constant.ReturnCodeInfoMap.get(errorCode);
		if (StringUtils.isEmpty(message)) {
			errorCode = Constant.ReturnCode.CODE_1110;
			message = e.getMessage();
		}
		result.addError(errorCode, message);
//		String methodName = joinPoint.getTarget().getClass().getSimpleName() + "." + joinPoint.getSignature().getName();
//		logger.info("返回参数:【{}】 IP:{} 终端:{} 出参:{}", methodName, ip, osName, result.toJson());
	}
}
